package com.financing.platform.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.financing.platform.activities.ActivitiesBusinessObject;
import com.financing.platform.activities.impl.ActivitiesYLYXHDImpl;
import com.financing.platform.dao.IActivitieGroupDao;
import com.financing.platform.dao.IAdvertDao;
import com.financing.platform.dao.IFaUserAuthDao;
import com.financing.platform.dao.IFaUserDao;
import com.financing.platform.dao.IFaUserVisitDao;
import com.financing.platform.dao.IManagerLicaishiDao;
import com.financing.platform.dao.IMessageDao;
import com.financing.platform.dao.IMessageMailDao;
import com.financing.platform.dao.IMessageNoteDao;
import com.financing.platform.dao.IMessageSmsDao;
import com.financing.platform.dao.IProductRecommendDao;
import com.financing.platform.dao.impl.SwitchDaoImpl;
import com.financing.platform.dto.ActivitiesGroupDTO;
import com.financing.platform.dto.AdvertDTO;
import com.financing.platform.dto.FaUserAuthDTO;
import com.financing.platform.dto.FaUserCertDTO;
import com.financing.platform.dto.FaUserDTO;
import com.financing.platform.dto.MessageDTO;
import com.financing.platform.dto.MessageMailDTO;
import com.financing.platform.dto.MessageNoteDTO;
import com.financing.platform.dto.MessageSmsDTO;
import com.financing.platform.dto.SwitchDTO;
import com.financing.platform.service.IActivitesService;
import com.financing.platform.service.IEmailTemplateService;
import com.financing.platform.service.IFaUserService;
import com.financing.platform.service.ISMSADService;
import com.financing.platform.service.ISwitchService;
import com.financing.platform.util.Dict;
import com.financing.platform.util.MemcacheCacheHelper;
import com.financing.platform.util.MessageUtil;
import com.financing.platform.util.SMSSend;
import com.financing.platform.util.StringUtil;
import com.financing.platform.vo.FaUserVO;
import com.financing.platform.vo.FaUserVisitStatisticVO;
import com.financing.platform.vo.ManagerLicaishiVO;

@Service("faUserServiceImpl")
@Transactional
public class FaUserServiceImpl extends BaseServiceImpl implements
		IFaUserService {

	@Autowired
	IFaUserDao faUserDaoImpl;
	
	@Autowired
	IFaUserAuthDao faUserAuthDaoImpl;
	
	@Autowired
	private IMessageDao messageDaoImpl;
	
	@Autowired
	private IMessageNoteDao messageNoteDaoImpl;
	
	@Autowired
	private IMessageSmsDao messageSmsDaoImpl;
	
	@Autowired
	private IActivitesService activitesServiceImpl;
	
	@Autowired
	private IEmailTemplateService emailTemplateServiceImpl;
	
	@Autowired
	private SwitchDaoImpl switchDaoImpl;
	
	@Autowired
	private IProductRecommendDao productRecommendDaoImpl;
	
	@Autowired
	private ISMSADService sMSAdServiceImpl ;
	
	@Autowired
	private IAdvertDao advertDaoImpl;
	
	@Autowired
	IManagerLicaishiDao managerLicaishiDao;
	
	@Autowired
	IActivitieGroupDao activitieGroupDao;
	
	@Autowired
	private IFaUserVisitDao faUserVisitDaoImpl;
	
	public List<FaUserDTO> queryAllFaUserInfo(FaUserDTO faUserDTO) {
		return faUserDaoImpl.getFaUserList(faUserDTO);
	}
	
	public List<FaUserDTO> queryAllShopFaUserInfo(FaUserDTO faUserDTO) {
		return faUserDaoImpl.getShopFaUserList(faUserDTO);
	}
	
	public FaUserDTO queryFaUserInfoView(FaUserDTO faUserDTO) throws SQLException{
		FaUserDTO user = faUserDaoImpl.getFaUserView(faUserDTO);
		if(user == null){
			return null;
		}
		//查询认证信息
		FaUserAuthDTO bean = new FaUserAuthDTO();
		bean.setFaId(faUserDTO.getId());
		bean =	faUserAuthDaoImpl.queryFaUserAuth(bean);
		//查询 分配信息
		ManagerLicaishiVO licaishiVo= new ManagerLicaishiVO();
		licaishiVo.setFaUserId(faUserDTO.getId());
		List<ManagerLicaishiVO> list = managerLicaishiDao.queryManagerLicaishiByForFirst(licaishiVo);
		licaishiVo = list.size()<=0?licaishiVo:list.get(0);
		//查询 回访信息
		FaUserVisitStatisticVO visitStatistic = faUserVisitDaoImpl.queryFaUserVisitStatistic(faUserDTO.getId());
		visitStatistic.setOrderCount(faUserDaoImpl.getFaUserOrderCount(faUserDTO.getId()));
		//订单信息
		user.setVisitStatisticVO(visitStatistic);
		user.setFaUserauth(bean);
		user.setLicaishiVO(licaishiVo);

		return user;
	}
	public FaUserDTO queryFaUserInfo(FaUserDTO faUserDTO){
		return faUserDaoImpl.getFaUser(faUserDTO);
	}
	@Override
	public int updateFaUserInfoShop(FaUserDTO faUserDTO) throws Exception {
		
		//合并审核
		FaUserDTO fu = mergeAuthsfajincs(faUserDTO);
		
		//修改成新的role
		fu.setuRole(faUserDTO.getuShopRole());
		fu.setuShopRole(faUserDTO.getuShopRole());
		//设置时间
		if(faUserDTO.getAuthDate()!=null){
			fu.setAuthDate(faUserDTO.getAuthDate());
		}
		
		int result = faUserDaoImpl.updateFaUserInfo(fu);
		
		if(faUserDTO.getuShopRole()!=null && (faUserDTO.getuShopRole().equals("99") || faUserDTO.getuShopRole().equals("2")) ){
			//发送短信通知
			FaUserDTO fauser = new FaUserDTO();
			fauser.setId(faUserDTO.getId());
			//查询fa手机号码
			fauser = faUserDaoImpl.getFaUser(fauser);
			String count="";
			Map<String, Object> msgMap = new HashMap<String,Object>();
			MessageSmsDTO messageSmsDTO = new MessageSmsDTO();
			//短信内容
			if(faUserDTO.getuShopRole().equals("99")){
				msgMap = MessageUtil.getMessage("shop","fail", msgMap);
				count = msgMap.get("content").toString();
				messageSmsDTO.setFpSmsType(Dict.shopVerifyNoPassSmsAd);
			}else if(faUserDTO.getuShopRole().equals("2")){
				msgMap = MessageUtil.getMessage("shop","success", msgMap);
				count = msgMap.get("content").toString();
				messageSmsDTO.setFpSmsType(Dict.shopVerifyPassSmsAd);
			} 
			
			//判断短信开关是否打开，打开则发送，不打开则永久不发送
			SwitchDTO switchs = new SwitchDTO();
			switchs.setsKey(messageSmsDTO.getFpSmsType());
			switchs = switchDaoImpl.querySwitch(switchs);
			if(Dict.switchOn.equals(switchs.getsValue())){
				List list = new ArrayList<String>();
				list.add(fauser.getuMobile());
				SMSSend sms= new SMSSend();
			    sms.sendSMS(list,count);
			}else{
			   log.info("switch is off ");
			}
		}
		
		return result;
	}
	@Override
	public int updateFaUserInfo(FaUserDTO faUserDTO) throws Exception {
		
		FaUserDTO fauser = mergeAuthsfajincs(faUserDTO);

		int result = faUserDaoImpl.updateFaUserInfo(faUserDTO);
		
		//注入活动  -fa用户认证
		try {
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("faUserDTO", faUserDTO);
			map.put("updateInt", result);
			activitesServiceImpl.ActivitiesJobExecutionObject(ActivitiesBusinessObject.handle_FaUser_Auth, map);
		} catch (Exception e) {
			log.error("updateFaUserADInfo ActivitiesJobExecutionObejct error", e);
		}
		
		if(!"1".equals(faUserDTO.getuRole()) && !"98".equals(faUserDTO.getuRole()) && ActivitiesYLYXHDImpl.activitiesCode.equals(fauser.getActSource())){
			ActivitiesGroupDTO agd = new ActivitiesGroupDTO();
			agd.setFpFaId(faUserDTO.getId());
//			List<ActivitiesGroupDTO> list = activitieGroupDao.queryActivitiesGroupInfo(agd);
//			if(null!=list&&(!list.isEmpty())){
				sendMessage(faUserDTO); 
//			}
		}
		
		
		
		
		MemcacheCacheHelper.mcc.add("userInfo_"+faUserDTO.getId(), faUserDTO.getuRole());
		return result;
	}
	/***
	 * 金策师超级理财师后台审核合并
	 * @param faUserDTO
	 * @return
	 * @throws SQLException
	 */
	private FaUserDTO mergeAuthsfajincs(FaUserDTO faUserDTO)
			throws SQLException {
		//判断是否需要写入认证时间
		FaUserDTO fauser = new FaUserDTO();
		fauser.setId(faUserDTO.getId());
		fauser = faUserDaoImpl.getFaUser(fauser);
		if("1".equals(fauser.getuRole()) || "99".equals(fauser.getuRole()) || "98".equals(fauser.getuRole())){
			//认证通过 写入认证时间
			if(!"1".equals(faUserDTO.getuRole()) &&  !"99".equals(faUserDTO.getuRole()) && !"98".equals(faUserDTO.getuRole())){
				faUserDTO.setAuthDate(faUserDTO.getUpdateDate());
				faUserDTO.setAuthByName(faUserDTO.getUpdateBy());
			}
		}
		
		FaUserAuthDTO faUserAuthDTO = new FaUserAuthDTO();
		FaUserCertDTO faUserCertDTO = new FaUserCertDTO();
		
		//认证通过-修改fp_fa_auth fp_fa_cert  审核通过
		if(!"1".equals(faUserDTO.getuRole()) &&  !"99".equals(faUserDTO.getuRole()) && !"98".equals(faUserDTO.getuRole())){
			faUserAuthDTO.setReviewStatus(Dict.fa_status_success);
			faUserCertDTO.setReviewStatus(Dict.fa_status_success);
		}else{
			faUserAuthDTO.setReviewStatus(Dict.fa_status_fail);
			faUserCertDTO.setReviewStatus(Dict.fa_status_fail);
		}
		
		faUserAuthDTO.setFaId(faUserDTO.getId());
		faUserAuthDTO.setUpdateBy(faUserDTO.getUpdateBy());
		faUserAuthDTO.setWechatNo(faUserDTO.getWechatNo());// 用户认证 增加的微信号
//		faUserAuthDaoImpl.updateFaUserAuth(faUserAuthDTO);
		
		// 判断是否有认证信息
		FaUserAuthDTO queryFaUserAuthDTO = new FaUserAuthDTO();
		queryFaUserAuthDTO.setFaId(faUserDTO.getId());
		queryFaUserAuthDTO = faUserAuthDaoImpl.queryFaUserAuth(queryFaUserAuthDTO);
		Map<String, Object> faUserAuthMap = new HashMap<String, Object>();
		faUserAuthMap.put("faId", faUserDTO.getId());
		faUserAuthMap.put("wechatNo", faUserDTO.getWechatNo());
		if(queryFaUserAuthDTO == null){
			faUserAuthDaoImpl.addFaUserAuth(faUserAuthMap);
		}else{
			faUserAuthDaoImpl.updateFaUserAuthAll(faUserAuthMap);
		}
		
		faUserCertDTO.setFaId(faUserDTO.getId());
		faUserCertDTO.setUpdateBy(faUserDTO.getUpdateBy());
		faUserAuthDaoImpl.updateFaUserCert(faUserCertDTO);
		return fauser;
	}
	
	private void sendMessage(FaUserDTO faUserDTO) throws Exception{
		
		FaUserDTO fauser = new FaUserDTO();
		fauser.setId(faUserDTO.getId());
		
		//查询fa手机号码
		fauser = faUserDaoImpl.getFaUser(fauser);
		
		//添加消息主体
		MessageDTO messageDTO = new MessageDTO();
		messageDTO.setFaId(faUserDTO.getId());
		messageDTO.setCreateBy("system");
		messageDTO.setCreateDate(new Date());
		messageDTO.setUpdateBy("system");
		messageDTO.setUpdateDate(new Date());
		messageDTO.setStatus(Dict.status_normal);
		
		Map<String, Object> msgMap = new HashMap<String,Object>();
		
		//组团活动审核未通过短信
		if("注册手机号码与名片手机号码不一致".equals(faUserDTO.getuAuditOpinion())){
			msgMap.put("uAuditOpinion","原因：名片手机号码与注册号码不一致。快去重新上传名片吧。");
		}else if("未上传名片或上传名片与资质要求不符".equals(faUserDTO.getuAuditOpinion())){
			msgMap.put("uAuditOpinion","原因：您提交的名片为图片、非实物印刷名片，或存在修改痕迹，请上传本人真实有效名片。 ");
		}else{
			msgMap.put("uAuditOpinion", "原因：非金融行业从业人员所属名片。您可以邀请身边的理财达人参与活动哦。");
		}
	//	msgMap.put("uAuditOpinion", faUserDTO.getuAuditOpinion());
		
		
		MessageSmsDTO messageSmsDTO = new MessageSmsDTO();
		
		Map<String,Object> mail = new HashMap<String, Object>();
		if(!StringUtil.isNullOrEmptyStr(fauser.getuEmail())){
			AdvertDTO advertDTO = new AdvertDTO();
			advertDTO.setAdvertPosition(Dict.ad_mail);
			List<AdvertDTO> list = advertDaoImpl.queryAdvertList(advertDTO);
			mail.put("userMobile", fauser.getuMobile());
			mail.put("list", productRecommendDaoImpl.getEmailTemplateProjectList(2));
			if(list != null && list.size()>0){
				advertDTO = list.get(0);
				mail.put("imageUrl", advertDTO.getPicAddre());
				mail.put("hrefUrl", advertDTO.getLinkAddre());
			}
			
		}
		
		if(Dict.fa_u_role.equals(faUserDTO.getuRole())){
			//短信内容
			msgMap = MessageUtil.getMessage("fa","fail", msgMap);
			msgMap.put("content", msgMap.get("content")+sMSAdServiceImpl.getSmsAd(Dict.faVerifyNoPassSmsAd));
			messageSmsDTO.setFpSmsType(Dict.faVerifyNoPassSmsAd);
			
			//邮件内容
			if(!StringUtil.isNullOrEmptyStr(fauser.getuEmail())){
				mail.put("causeBy", faUserDTO.getuAuditOpinion());
				mail = emailTemplateServiceImpl.spliceEmailContent(Dict.mail_template_fa_verify_fail, mail);
				mail.put("mail_switch", Dict.mail_fa_verify_fail);
			}
		}else{
			msgMap = MessageUtil.getMessage("fa","success", msgMap);
			msgMap.put("content", msgMap.get("content")+sMSAdServiceImpl.getSmsAd(Dict.faVerifyPassSmsAd));
			messageSmsDTO.setFpSmsType(Dict.faVerifyPassSmsAd);
			//邮件内容
			if(!StringUtil.isNullOrEmptyStr(fauser.getuEmail())){
				mail = emailTemplateServiceImpl.spliceEmailContent(Dict.mail_template_fa_verify_success, mail);
				mail.put("mail_switch", Dict.mail_fa_verify_success);
			}
		}
		
		messageDTO.setMsgTitle((String)msgMap.get(Dict.message_title));
		messageDTO.setMsgContent((String)msgMap.get(Dict.message_content));
		messageDTO.setMsgType(Dict.message_type_fa);
		
		messageDTO.setPublicDate( new Date());
		messageDTO.setEndDate(StringUtil.rollDay( new Date(), 10));
		
		int messageId = messageDaoImpl.addMessage(messageDTO);
		
		//添加站内消息
		MessageNoteDTO messageNoteDTO = new MessageNoteDTO();
		messageNoteDTO.setCreateBy(faUserDTO.getUpdateBy());
		messageNoteDTO.setCreateDate(faUserDTO.getUpdateDate());
		messageNoteDTO.setUpdateBy(faUserDTO.getUpdateBy());
		messageNoteDTO.setUpdateDate(faUserDTO.getUpdateDate());
		messageNoteDTO.setFaId(faUserDTO.getId());
		messageNoteDTO.setMsgId(messageId);
		messageNoteDTO.setMsgStatus(Dict.message_note_status);
		messageNoteDTO.setStatus(Dict.status_normal);
		
		// messageNoteDaoImpl.addMessageNote(messageNoteDTO);
		
		//添加短信息
		messageSmsDTO.setCreateBy(messageDTO.getUpdateBy());
		messageSmsDTO.setUpdateBy(messageDTO.getUpdateBy());
		messageSmsDTO.setCreateDate(messageDTO.getUpdateDate());
		messageSmsDTO.setUpdateDate(messageDTO.getUpdateDate());
		messageSmsDTO.setFpSmsMessageId(messageId);
		messageSmsDTO.setFpSmsContent(messageDTO.getMsgContent());
		messageSmsDTO.setFpSmsSendType(Dict.message_type_now);
		messageSmsDTO.setStatus(Dict.status_normal);
		messageSmsDTO.setFpSmsSendStatus(Dict.message_status_not_send);
		
		
		messageSmsDTO.setFpSmsRecivePhoneNo(fauser.getuLoginName());
		
		messageSmsDaoImpl.addMessageSms(messageSmsDTO);
		
		//发送邮件
		if(!StringUtil.isNullOrEmptyStr(fauser.getuEmail())){
			MessageMailDTO messageMailDTO = new MessageMailDTO();
			messageMailDTO.setFpMailContent((String)mail.get(Dict.mail_content));
			messageMailDTO.setFpMailTitle((String)mail.get(Dict.mail_subject));
			messageMailDTO.setFpMailType((String)mail.get("mail_switch"));
			messageMailDTO.setFpMailSendType(Dict.message_type_now);
			messageMailDTO.setFpMailSendTimes(new Integer(0));
			messageMailDTO.setFpMailTo(fauser.getuEmail());
			messageMailDTO.setStatus(Dict.status_normal);
			messageMailDTO.setFpMailSendStatus(Dict.message_status_not_send);
			messageMailDTO.setCreateBy(messageDTO.getUpdateBy());
			messageMailDTO.setUpdateBy(messageDTO.getUpdateBy());
			messageMailDTO.setCreateDate(messageDTO.getUpdateDate());
			messageMailDTO.setUpdateDate(messageDTO.getUpdateDate());
		//	messageMailDaoImpl.addMessageMail(messageMailDTO);
		}
		
}

	@Override
	public int updateFaUserADInfo(FaUserDTO faUserDTO) throws SQLException {
		
		//认证通过 写入认证时间
		if(!"1".equals(faUserDTO.getuRole()) &&  !"99".equals(faUserDTO.getuRole()) && !"98".equals(faUserDTO.getuRole())){
			faUserDTO.setAuthDate(faUserDTO.getUpdateDate());
		}
		
		int updateInt = faUserDaoImpl.updateFaUserInfo(faUserDTO);
		
		//注入活动  -fa用户认证
		try {
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("faUserDTO", faUserDTO);
			map.put("updateInt", updateInt);
			activitesServiceImpl.ActivitiesJobExecutionObject(ActivitiesBusinessObject.handle_FaUser_Auth, map);
		} catch (Exception e) {
			log.error("updateFaUserADInfo ActivitiesJobExecutionObejct error", e);
		}
		return updateInt;
	}

	@Override
	public int queryAllFaUserInfoCount(FaUserDTO faUserDTO) throws SQLException {
		return faUserDaoImpl.getFaUserListCount(faUserDTO);
	}
	
	@Override
	public int queryAllShopFaUserInfoCount(FaUserDTO faUserDTO) throws SQLException {
		return faUserDaoImpl.getShopFaUserListCount(faUserDTO);
	}

	@Override
	public List<FaUserVO> queryFaUserListAuthPass(FaUserDTO faUserDTO) throws SQLException{
		return faUserDaoImpl.queryFaUserListAuthPass(faUserDTO);
	}

	@Override
	public int queryFaUserListAuthPassCount(FaUserDTO faUserDTO)
			throws SQLException {
		return faUserDaoImpl.queryFaUserListAuthPassCount(faUserDTO);
	}

	@Override
	public int querySingleFaUserListAuthPassCount(FaUserDTO faUserDTO)
			throws SQLException {
		return faUserDaoImpl.querySingleFaUserListAuthPassCount(faUserDTO);
	}

	@Override
	public List<FaUserDTO> querySingleFaUserListAuthPass(FaUserDTO faUserDTO)
			throws SQLException {
		return faUserDaoImpl.querySingleFaUserListAuthPass(faUserDTO);
	}

	@Override
	public int updateFaUserCert(FaUserDTO faUserDTO) throws SQLException {
		return faUserDaoImpl.updateFaUserInfo(faUserDTO);
	}
	@Override
	public void updateFaUserForVisit(Map<String, Object> map)
			throws SQLException {
		faUserDaoImpl.updateFaUserInfoForMap(map);
		
		//查询 -存在修改-  不存在-添加
		FaUserAuthDTO faUserAuthDTO = new FaUserAuthDTO();
		faUserAuthDTO.setFaId((String) map.get("faId"));
		faUserAuthDTO = faUserAuthDaoImpl.queryFaUserAuth(faUserAuthDTO);
		if(faUserAuthDTO == null){
			faUserAuthDaoImpl.addFaUserAuth(map);
		}else{
			
			faUserAuthDaoImpl.updateFaUserAuthAll(map);
		}
		
	}
	@Override
	public List<String> queryFaUserSubUserId(String systemUserId) throws SQLException {
		Map<String,String> map = new HashMap<String, String>();
		map.put("systemUserId",systemUserId);
		return faUserDaoImpl.queryFaUserSubUserId(map);
	}
	@Override
	public List<String> queryFaUserSubUserId(String systemUserId,String job) throws SQLException {
		Map<String,String> map = new HashMap<String, String>();
		map.put("systemUserId",systemUserId);
		map.put("remark",job);
		return faUserDaoImpl.queryFaUserSubUserId(map);
	}
	@Override
	public FaUserDTO getFaUserView(FaUserDTO fauserDTO) throws SQLException {
		return faUserDaoImpl.getFaUserView(fauserDTO);
	}

	@Override
	public List<String> queryActSource() throws SQLException {
		return faUserDaoImpl.queryActSource();
	}

	@Override
	public List<FaUserDTO> queryAllFaUserInfoBasic(FaUserDTO faUserDTO) throws SQLException {
		return faUserDaoImpl.queryAllFaUserInfoBasic(faUserDTO);
	}

	@Override
	public String queryFrontLicaishiManagerUser(String id) throws SQLException {
		return faUserDaoImpl.queryFrontLicaishiManagerUser(id);
	}

	@Override
	public int queryAllFaUserSystemRateCount(FaUserDTO faUserDTO) throws SQLException {
		return faUserDaoImpl.queryAllFaUserSystemRateCount(faUserDTO);
	}

	@Override
	public List<FaUserDTO> queryAllFaUserSystemRate(FaUserDTO faUserDTO) throws SQLException {
		return faUserDaoImpl.queryAllFaUserSystemRate(faUserDTO);
	}

	@Override
	public void updateFaUserSystemRate(FaUserDTO faUserDTO) throws SQLException {
		faUserDaoImpl.updateFaUserSystemRate(faUserDTO);
	}

	@Override
	public List<FaUserDTO> queryFaUserNomanager(String date)
			throws SQLException {
		return faUserDaoImpl.queryFaUserNomanager(date);
	}
}